'''
runbatch.py

process all repository, generate the following
	1 SQLite database
	2 HTML Report
	3 CSV report for Excel
'''

import os, os.path, sys
from datetime import datetime
import svnlog2sqlite, svnplot, svnstats
import argparse

import config
    
def updatedb(name, svnpath, user, password, excludes):
    #create db folder if not exist
    dbpath = os.path.join(config.ROOTPATH, config.DBPATH)
    if not os.path.exists(dbpath):
        os.makedirs(dbpath)
        
    dbpath = os.path.join(dbpath, name) + '.sqlite'
    print "Generating database: " + dbpath
    
    starttime= svnlog2sqlite.parse_svndate(config.STARTDATE)
    endtime = svnlog2sqlite.parse_svndate(datetime.now().strftime('{%Y-%m-%d}'))
    
    #convert svn log to database
    conv = svnlog2sqlite.SVNLog2Sqlite(svnpath, dbpath, username=user, password=password, excludes=excludes)
    conv.convert(starttime, endtime, True)
    
    return dbpath
    
def updatereport(name, dbpath):
    #create report path if not exist
    reportpath = os.path.join(config.ROOTPATH, config.REPORTPATH, name)
    if not os.path.exists(reportpath):
        os.makedirs(reportpath)
        
    print "Generating report at: " + reportpath
    
    #create report
    stats = svnstats.SVNStats(dbpath)     
    plot = svnplot.SVNPlot(stats)
    plot.SetRepoName(name)
    plot.AllGraphs(reportpath, '/', 100, 10)        
    
def updatecsv(name, dbpath):
    #create csv path if not exist
    csvpath = os.path.join(config.ROOTPATH, config.CSVPATH)
    if not os.path.exists(csvpath):
        os.makedirs(csvpath)
        
    csvpath = os.path.join(csvpath, name) + '.csv'
    print "Generating csv report: " + csvpath
    
    #create csv
    #write csv to all projects
    
def runmain():
    parser = argparse.ArgumentParser(description='SVN Project Analysis Tool')
    parser.add_argument('-p', '--project', help='select project by name in config')
    parser.add_argument('-a', '--all', action='store_true', default=False, help='analyse all projects in config')
    
    args = parser.parse_args()
    if args.all:
        projects = config.projects
    else:
        for project in config.projects:
            if project['name']==args.project:
                projects = [project]

    for project in projects:
        dbpath = updatedb(project['name'], project['repo'], project['user'], project['pass'], project['excludes']) 
        
        updatereport(project['name'], dbpath)
        
        #updatecsv(project['name'], dbpath)
        
        
        
if( __name__ == "__main__"):
    runmain()

